home *** CD-ROM | disk | FTP | other *** search
/ Info-Mac 3 / Info_Mac_1994-01.iso / Development / Information / Mac Programming Secrets 1.0.1 / Chapter 06 / Standard Stuff.c < prev    next >
C/C++ Source or Header  |  1992-05-19  |  20KB  |  669 lines

  1. #include "Standard Stuff.h"
  2. #include "Neat Stuff.h"
  3. #include "Traps.h"
  4.  
  5. /*******************************************************************************
  6.  
  7.     The “g” prefix is used to emphasize that a variable is global.
  8.  
  9. *******************************************************************************/
  10.  
  11. SysEnvRec    gMac;                /*    gMac is used to hold the result of a
  12.                                     SysEnvirons call. This makes it convenient
  13.                                     for any routine to check the environment. */
  14.  
  15. Boolean        gQuit;                /*    We set this to TRUE when the user selects
  16.                                     Quit from the File menu. Our main event
  17.                                     loop exists when gQuit is TRUE. */
  18.  
  19. Boolean        gInBackground;        /*    gInBackground is maintained by our osEvent
  20.                                     handling routines. Any part of the program
  21.                                     can check it to find out if it is currently
  22.                                     in the background. */
  23.  
  24.  
  25. /*******************************************************************************
  26.  
  27.     Define HiWrd and LoWrd macros for efficiency.
  28.  
  29. *******************************************************************************/
  30.  
  31. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  32. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  33.  
  34.  
  35. /*******************************************************************************
  36.  
  37.     main
  38.  
  39.     Entry point for our program. We initialize the toolbox, make sure we are
  40.     running on a sufficiently studly machine, and put up the menubar. Finally,
  41.     we start polling for events and handling them by entering our main event
  42.     loop.
  43.  
  44. *******************************************************************************/
  45. main()
  46. {
  47.     /*    If you have stack requirements that differ from the default,
  48.         then you could use SetApplLimit to increase StackSpace at
  49.         this point, before calling MaxApplZone. */
  50.  
  51.     MaxApplZone();                    /* Expand the heap so code segments load
  52.                                        at the top */
  53.     InitToolbox();                    /* Initialize the program */
  54.     MainEventLoop();                /* Call the main event loop */
  55. }
  56.  
  57.  
  58. /*******************************************************************************
  59.  
  60.     InitToolbox
  61.  
  62.     Set up the whole world, including global variables, Toolbox managers, and
  63.     menus.
  64.  
  65. *******************************************************************************/
  66. void InitToolbox()
  67. {
  68.     Handle        menuBar;
  69.     EventRecord event;
  70.     short        count;
  71.  
  72.     gInBackground = FALSE;
  73.     gQuit = FALSE;
  74.  
  75.     InitGraf((Ptr) &qd.thePort);
  76.     InitFonts();
  77.     InitWindows();
  78.     InitMenus();
  79.     TEInit();
  80.     InitDialogs(NIL);
  81.     InitCursor();
  82.  
  83.     /*    This next bit of code waits until MultiFinder brings our application
  84.         to the front. This gives us a better effect if we open a window at
  85.         startup. */
  86.  
  87.     for (count = 1; count <= 3; ++count)
  88.         EventAvail(everyEvent, &event);
  89.  
  90.     SysEnvirons(curSysEnvVers, &gMac);
  91.  
  92.     if (gMac.machineType < 0)
  93.         DeathAlert(errWimpyROMs);
  94.  
  95.     if (gMac.systemVersion < 0x0600)
  96.         DeathAlert(errWimpySystem);
  97.  
  98.     if (!TrapExists(_WaitNextEvent))
  99.         DeathAlert(errWeirdSystem);
  100.  
  101.     menuBar = GetNewMBar(rMenuBar);            /* Read menus into menu bar */
  102.     if ( menuBar == NIL )
  103.          DeathAlert(errNoMenuBar);
  104.     SetMenuBar(menuBar);                    /* Install menus */
  105.     DisposHandle(menuBar);
  106.     AddResMenu(GetMHandle(mApple), 'DRVR');    /* Add DA names to Apple menu */
  107.     AdjustMenus();
  108.     DrawMenuBar();
  109. }
  110.  
  111.  
  112. /*******************************************************************************
  113.  
  114.     MainEventLoop
  115.  
  116.     Get events forever, and handle them by calling HandleEvent. First, call
  117.     DoAdjustCursor to set our cursor shape, and to set the cursor region. We
  118.     then call WaitNextEvent() to get the event. This is OK, because we know
  119.     we’re running on System 6.0 or later by this time. If we got an event, we
  120.     handle it by calling HandleEvent(). But before doing that, we call
  121.     DoAdjustCursor again in case our application had fallen asleep under
  122.     MultiFinder.
  123.  
  124. *******************************************************************************/
  125. void MainEventLoop()
  126. {
  127.     RgnHandle    cursorRgn;
  128.     Boolean        gotEvent;
  129.     EventRecord    event;
  130.     Point        mouse;
  131.  
  132.     cursorRgn = NIL;
  133.     while ( !gQuit ) {
  134.         gotEvent = WaitNextEvent(everyEvent, &event, 1, cursorRgn);    /* +++ */
  135.         /* if ( gotEvent ) { */                                        /* +++ */
  136.             HandleEvent(&event);
  137.         /* } */                                                        /* +++ */
  138.     }
  139. }
  140.  
  141.  
  142. /*******************************************************************************
  143.  
  144.     HandleEvent
  145.  
  146.     Do the right thing for an event. Determine what kind of event it is, and
  147.     call the appropriate routines.
  148.  
  149. *******************************************************************************/
  150. void HandleEvent(EventRecord *event)
  151. {
  152.     switch ( event->what ) {
  153.         case nullEvent:                                                /* +++ */
  154.             DoMarchingAnts();                                        /* +++ */
  155.             break;                                                    /* +++ */
  156.         case mouseDown:
  157.             HandleMouseDown(event);
  158.             break;
  159.         case keyDown:
  160.         case autoKey:
  161.             HandleKeyPress(event);
  162.             break;
  163.         case activateEvt:
  164.             HandleActivate(event);
  165.             break;
  166.         case updateEvt:
  167.             HandleUpdate(event);
  168.             break;
  169.         case diskEvt:
  170.             HandleDiskInsert(event);
  171.             break;
  172.         case osEvt:
  173.             HandleOSEvent(event);
  174.             break;
  175.     }
  176. }
  177.  
  178.  
  179. /*******************************************************************************
  180.  
  181.     HandleActivate
  182.  
  183.     This is called when a window is activated or deactivated. In this sample,
  184.     the Window Manager’s handling of activate and deactivate events is
  185.     sufficient. Other applications may have TextEdit records, controls, lists,
  186.     etc., to activate/deactivate.
  187.  
  188. *******************************************************************************/
  189. void HandleActivate(EventRecord *event)
  190. {
  191.     WindowPtr    theWindow;
  192.     Boolean        becomingActive;
  193.  
  194.     theWindow = (WindowPtr) event->message;
  195.     becomingActive = (event->modifiers & activeFlag) != 0;
  196.     if ( IsAppWindow(theWindow) ) {
  197.         DoDrawGrowIcon(theWindow);                                    /* +++ */
  198.         DoActivateWindow(theWindow, becomingActive);                /* +++ */
  199.     }
  200. }
  201.  
  202.  
  203. /*******************************************************************************
  204.  
  205.     HandleDiskInsert
  206.  
  207.     Called when we get a disk inserted event. Check the upper word of the
  208.     event message; if it’s non-zero, then a bad disk was inserted, and it
  209.     needs to be formatted.
  210.  
  211. *******************************************************************************/
  212. void HandleDiskInsert(EventRecord *event)
  213. {
  214.     Point    aPoint = {100, 100};
  215.  
  216.     if ( HiWrd(event->message) != noErr ) {
  217.         (void) DIBadMount(aPoint, event->message);
  218.     }
  219. }
  220.  
  221.  
  222. /*******************************************************************************
  223.  
  224.     HandleKeyPress
  225.  
  226.     The user pressed a key. What are you going to do about it?
  227.  
  228. *******************************************************************************/
  229. void HandleKeyPress(EventRecord *event)
  230. {
  231.     char    key;
  232.  
  233.     key = event->message & charCodeMask;
  234.     if ( event->modifiers & cmdKey ) {        /* Command key down? */
  235.         AdjustMenus();                        /* Enable/disable/check menu items properly */
  236.         HandleMenuCommand(MenuKey(key));
  237.     } else {
  238.         /* DoKeyPress(event) */;
  239.     }
  240. }
  241.  
  242.  
  243. /*******************************************************************************
  244.  
  245.     HandleMouseDown
  246.  
  247.     Called to handle mouse clicks. The user could have clicked anywhere, so
  248.     let’s first find out where by calling FindWindow. That returns a number
  249.     indicating where in the screen the mouse was clicked. “switch” on that
  250.     number and call the appropriate routine.
  251.  
  252. *******************************************************************************/
  253. void HandleMouseDown(EventRecord *event)
  254. {
  255.     long        newSize;
  256.     Rect        growRect;
  257.     WindowPtr    theWindow;
  258.     short        part = FindWindow(event->where, &theWindow);
  259.  
  260.     switch ( part ) {
  261.         case inMenuBar:                /* Process a mouse menu command (if any) */
  262.             AdjustMenus();
  263.             HandleMenuCommand(MenuSelect(event->where));
  264.             break;
  265.         case inSysWindow:            /* Let the system handle the mouseDown */
  266.             SystemClick(event, theWindow);
  267.             break;
  268.         case inContent:
  269.             if ( theWindow != FrontWindow() )
  270.                 SelectWindow(theWindow);
  271.             else
  272.                 DoContentClick(event, theWindow);                    /* +++ */
  273.             break;
  274.         case inDrag:                /* Pass screenBits.bounds to get all gDevices */
  275.             DragWindow(theWindow, event->where, &qd.screenBits.bounds);
  276.             break;
  277.         case inGrow:
  278.             growRect = qd.screenBits.bounds;
  279.             growRect.top = growRect.left = 80;        /* Arbitrary minimum size. */
  280.             newSize = GrowWindow(theWindow, event->where, &growRect);
  281.             if (newSize != 0) {
  282.                 InvalidateScrollbars(theWindow);
  283.                 SizeWindow(theWindow, LoWrd(newSize), HiWrd(newSize), TRUE);
  284.                 InvalidateScrollbars(theWindow);
  285.             }
  286.             break;
  287.         case inGoAway:
  288.             if (TrackGoAway(theWindow, event->where))  {
  289.                 CloseAnyWindow(theWindow);
  290.             }
  291.             break;
  292.         case inZoomIn:
  293.         case inZoomOut:
  294.             if (TrackBox(theWindow, event->where, part)) {
  295.                 SetPort(theWindow);
  296.                 EraseRect(&theWindow->portRect);
  297.                 ZoomWindow(theWindow, part, TRUE);
  298.                 InvalRect(&theWindow->portRect);
  299.             }
  300.             break;
  301.     }
  302. }
  303.  
  304.  
  305. /*******************************************************************************
  306.  
  307.     HandleOSEvent
  308.  
  309.     Deal with OSEvents (formerly, app4Events). These are message that
  310.     MultiFinder -- known as the Process Manager under System 7.0 -- sends to
  311.     us. Here, we deal with suspend and resume message.
  312.  
  313. *******************************************************************************/
  314. void HandleOSEvent(EventRecord *event)
  315. {
  316.     switch ((event->message >> 24) & 0x00FF) {        /* High byte of message */
  317.         case suspendResumeMessage:
  318.  
  319.             /*    In our SIZE resource, we say that we are MultiFinder aware.
  320.                 This means that we take on the responsibility of activating
  321.                 and deactivating our own windows on suspend/resume events. */
  322.  
  323.             gInBackground = (event->message & resumeFlag) == 0;
  324.             if (FrontWindow()) {
  325.                 DoDrawGrowIcon(FrontWindow());                        /* +++ */
  326.                 DoActivateWindow(FrontWindow(), !gInBackground);    /* +++ */
  327.             }
  328.             break;
  329.         case mouseMovedMessage:
  330.             break;
  331.     }
  332. }
  333.  
  334.  
  335. /*******************************************************************************
  336.  
  337.     HandleUpdate
  338.  
  339.     This is called when an update event is received for a window. It calls
  340.     DoUpdateWindow to draw the contents of an application window. As an
  341.     efficiency measure that does not have to be followed, it calls the drawing
  342.     routine only if the visRgn is non-empty. This will handle situations where
  343.     calculations for drawing or drawing itself is very time-consuming.
  344.  
  345. *******************************************************************************/
  346. void HandleUpdate(EventRecord *event)
  347. {
  348.     WindowPtr    theWindow = (WindowPtr) event->message;
  349.     if ( IsAppWindow(theWindow) ) {
  350.         BeginUpdate(theWindow);                /* This sets up the visRgn */
  351.         if (!EmptyRgn(theWindow->visRgn)) {    /* Draw if updating needs to be done */
  352.             SetPort(theWindow);
  353.             EraseRgn(theWindow->visRgn);
  354.             DoUpdateWindow(event);                                    /* +++ */
  355.             DoDrawGrowIcon(theWindow);                                /* +++ */
  356.         }
  357.         EndUpdate(theWindow);
  358.     }
  359. }
  360.  
  361.  
  362. /*******************************************************************************
  363.  
  364.     AdjustMenus
  365.  
  366.     Enable and disable menus based on the current state. The user can only
  367.     select enabled menu items. We set up all the menu items before calling
  368.     MenuSelect or MenuKey, since these are the only times that a menu item can
  369.     be selected. Note that MenuSelect is also the only time the user will see
  370.     menu items. This approach to deciding what enable/disable state a menu
  371.     item has the advantage of concentrating all the decision-making in one
  372.     routine, as opposed to being spread throughout the application. Other
  373.     application designs may take a different approach that is just as valid.
  374.  
  375. *******************************************************************************/
  376. void AdjustMenus()
  377. {
  378.     WindowPtr    window;
  379.     MenuHandle    menu;
  380.  
  381.     window = FrontWindow();
  382.  
  383.     menu = GetMHandle(mFile);
  384.     EnableItem(menu, iOpen);                                        /* +++ */
  385.     if ( window != NIL )
  386.         EnableItem(menu, iClose);
  387.     else
  388.         DisableItem(menu, iClose);
  389.  
  390.     menu = GetMHandle(mEdit);
  391.     if ( IsDAWindow(window) ) {        /* A desk accessory might need the edit menu… */
  392.         EnableItem(menu, iUndo);
  393.         EnableItem(menu, iCut);
  394.         EnableItem(menu, iCopy);
  395.         EnableItem(menu, iClear);
  396.         EnableItem(menu, iPaste);
  397.     } else {                        /* … but we don’t use it. */
  398.         DisableItem(menu, iUndo);
  399.         DisableItem(menu, iCut);
  400.         DisableItem(menu, iCopy);
  401.         DisableItem(menu, iClear);
  402.         DisableItem(menu, iPaste);
  403.     }
  404. }
  405.  
  406.  
  407. /*******************************************************************************
  408.  
  409.     HandleMenuCommand
  410.  
  411.     This is called when an item is chosen from the menu bar (after calling
  412.     MenuSelect or MenuKey). It performs the right operation for each command.
  413.     It is good to have both the result of MenuSelect and MenuKey go to one
  414.     routine like this to keep everything organized.
  415.  
  416. *******************************************************************************/
  417. void HandleMenuCommand(menuResult)
  418.     long        menuResult;
  419. {
  420.     short        menuID;                /* The resource ID of the selected menu */
  421.     short        menuItem;            /* The item number of the selected menu */
  422.     Str255        daName;
  423.  
  424.     menuID = HiWrd(menuResult);
  425.     menuItem = LoWrd(menuResult);
  426.     switch ( menuID ) {
  427.         case mApple:
  428.             switch ( menuItem ) {
  429.                 case iAbout:
  430.                     (void) Alert(rAboutAlert, NIL);
  431.                     break;
  432.                 default:            /* All non-About items in this menu are DAs */
  433.                     GetItem(GetMHandle(mApple), menuItem, daName);
  434.                     (void) OpenDeskAcc(daName);
  435.                     break;
  436.             }
  437.             break;
  438.         case mFile:
  439.             switch ( menuItem ) {
  440.                 case iNew:
  441.                     /* DoNewWindow(); */
  442.                     break;
  443.                 case iOpen:                                            /* +++ */
  444.                     DoOpenWindow();                                    /* +++ */
  445.                     break;                                            /* +++ */
  446.                 case iClose:
  447.                     CloseAnyWindow(FrontWindow());
  448.                     break;
  449.                 case iQuit:
  450.                     gQuit = TRUE;
  451.                     break;
  452.             }
  453.             break;
  454.         case mEdit:
  455.             switch (menuItem) {
  456.                 /* Call SystemEdit for DA editing & MultiFinder */
  457.                 /* since we don’t do any Editing */
  458.                 case iUndo:
  459.                 case iCut:
  460.                 case iCopy:
  461.                 case iPaste:
  462.                 case iClear:
  463.                     (void) SystemEdit(menuItem-1);
  464.                     break;
  465.             }
  466.             break;
  467.     }
  468.     HiliteMenu(0);        /* Unhighlight what MenuSelect or MenuKey hilited */
  469. }
  470.  
  471.  
  472. /*******************************************************************************
  473.  
  474.     CloseAnyWindow
  475.  
  476.     Close the given window in a manner appropriate for that window. If the
  477.     window belongs to a DA, we call CloseDeskAcc. For dialogs, we simply hide
  478.     the window. If we had any document windows, we would probably call either
  479.     DisposeWindow or CloseWindow after disposing of any document data and/or
  480.     controls.
  481.  
  482. *******************************************************************************/
  483. void CloseAnyWindow(WindowPtr window)
  484. {
  485.     if (IsDAWindow(window)) {
  486.         CloseDeskAcc( ( (WindowPeek) window )->windowKind );
  487.     } else if (IsDialogWindow(window)) {
  488.         HideWindow(window);
  489.     } else if (IsAppWindow(window)) {
  490.         DoCloseWindow(window);                                        /* +++ */
  491.     }
  492. }
  493.  
  494.  
  495. /*******************************************************************************
  496.  
  497.     DeathAlert
  498.  
  499.     Display an alert that tells the user an error occurred, then exit the
  500.     program. This routine is used as an ultimate bail-out for serious errors
  501.     that prohibit the continuation of the application. The error number is
  502.     used to index an 'STR#' resource so that a relevant message can be
  503.     displayed.
  504.  
  505. *******************************************************************************/
  506. void DeathAlert(short errNumber)
  507. {
  508.     short        itemHit;
  509.     Str255        theMessage;
  510.  
  511.     SetCursor(&qd.arrow);
  512.     GetIndString(theMessage, rErrorStrings, errNumber);
  513.     ParamText(theMessage, NIL, NIL, NIL);
  514.     itemHit = StopAlert(rErrorAlert, NIL);
  515.     ExitToShell();
  516. }
  517.  
  518.  
  519. /*******************************************************************************
  520.  
  521.     IsAppWindow
  522.  
  523.     Check to see if a window belongs to the application. If the window pointer
  524.     passed was NIL, then it could not be an application window. WindowKinds
  525.     that are negative belong to the system and windowKinds less than userKind
  526.     are reserved by Apple except for windowKinds equal to dialogKind, which
  527.     mean it is a dialog.
  528.  
  529. *******************************************************************************/
  530. Boolean IsAppWindow(WindowPtr window)
  531. {
  532.     short        windowKind;
  533.  
  534.     if ( window == NIL )
  535.         return false;
  536.     else {
  537.         windowKind = ((WindowPeek) window)->windowKind;
  538.         return ((windowKind >= userKind) || (windowKind == dialogKind));
  539.     }
  540. }
  541.  
  542.  
  543. /*******************************************************************************
  544.  
  545.     IsDAWindow
  546.  
  547.     Check to see if a window belongs to a desk accessory. It belongs to a DA
  548.     if the windowKind field of the window record is negative.
  549.  
  550. *******************************************************************************/
  551. Boolean IsDAWindow(WindowPtr window)
  552. {
  553.     if ( window == NIL )
  554.         return false;
  555.     else
  556.         return ( ((WindowPeek) window)->windowKind < 0 );
  557. }
  558.  
  559.  
  560. /*******************************************************************************
  561.  
  562.     IsDialogWindow
  563.  
  564.     Check to see if a window is a dialog window. We can determine this be
  565.     checking to see if the windowKind field is equal to dialogKind.
  566.  
  567. *******************************************************************************/
  568. Boolean IsDialogWindow(WindowPtr window)
  569. {
  570.     if ( window == NIL )
  571.         return false;
  572.     else
  573.         return ( ((WindowPeek) window)->windowKind == dialogKind );
  574. }
  575.  
  576.  
  577. /*******************************************************************************
  578.  
  579.     InvalidateScrollbars
  580.  
  581.     Call InvalRect on the right and bottom edges of a window. This routine is
  582.     called during the resizing of a window to take care of the scrollbar lines
  583.     and grow icon.
  584.  
  585. *******************************************************************************/
  586. void InvalidateScrollbars(WindowPtr theWindow)
  587. {
  588.     Rect    tempRect;
  589.  
  590.     SetPort(theWindow);
  591.  
  592.     tempRect = theWindow->portRect;
  593.     tempRect.left = tempRect.right - 15;
  594.     InvalRect(&tempRect);
  595.     EraseRect(&tempRect);
  596.  
  597.     tempRect = theWindow->portRect;
  598.     tempRect.top = tempRect.bottom - 15;
  599.     InvalRect(&tempRect);
  600.     EraseRect(&tempRect);
  601. }
  602.  
  603.  
  604. /*******************************************************************************
  605.  
  606.     TrapExists
  607.  
  608.     Check to see if a given trap is implemented. The recommended approach to
  609.     see if a trap is implemented is to see if the address of the trap routine
  610.     is the same as the address of the _Unimplemented trap. However, we must
  611.     also make sure that the trap is contained in the trap table on the machine
  612.     we’re running on. Not all Macintoshes have the same sized trap tables. We
  613.     call NumToolboxTraps to find out the size of the table. If the trap we are
  614.     examining falls off the end, then we treat it as automatically being
  615.     unimplemented.
  616.  
  617. *******************************************************************************/
  618. Boolean    TrapExists(short theTrap)
  619. {
  620.     TrapType    theTrapType;
  621.  
  622.     theTrapType = GetTrapType(theTrap);
  623.     if ((theTrapType == ToolTrap) && ((theTrap &= 0x07FF) >= NumToolboxTraps()))
  624.         return false;
  625.     else
  626.         return (NGetTrapAddress(_Unimplemented, ToolTrap) !=
  627.                 NGetTrapAddress(theTrap, theTrapType));
  628. }
  629.  
  630.  
  631. /*******************************************************************************
  632.  
  633.     GetTrapType
  634.  
  635.     Check the bits of a trap number to determine its type. If bit 11 is set,
  636.     it’s a toolbox trap. Otherwise, it’s an OS trap.
  637.  
  638. *******************************************************************************/
  639. TrapType    GetTrapType(short theTrap)
  640. {
  641.     if ((theTrap & 0x0800) == 0)                    /* Per D.A. */
  642.         return (OSTrap);
  643.     else
  644.         return (ToolTrap);
  645. }
  646.  
  647.  
  648. /*******************************************************************************
  649.  
  650.     NumToolboxTraps
  651.  
  652.     Find the size of the Toolbox trap table. This can be either 0x0200 or
  653.     0x0400 bytes, depending on which Macintosh we are running on. We determine
  654.     the size by taking advantage of an anomaly of the smaller trap table: any
  655.     entries that fall beyond the end of the table are mirrored back down into
  656.     the lower part. For example, on a large table, trap numbers A86E and AA6E
  657.     correspond to different routines. However, on a small table, they
  658.     correspond to the same routine. By checking the addresses of these
  659.     routines, we can determine the size of the table.
  660.  
  661. *******************************************************************************/
  662. short    NumToolboxTraps(void)
  663. {
  664.     if (NGetTrapAddress(0xA86E, ToolTrap) == NGetTrapAddress(0xAA6E, ToolTrap))
  665.         return (0x200);
  666.     else
  667.         return (0x400);
  668. }
  669.